package com.dongway.netcondition.security;

import java.util.Arrays;
import java.util.HashSet;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dongway.core.store.JdbcDAO;
import com.dongway.netcondition.model.User;


@Component
public class SimpleRealm extends AuthorizingRealm {

    @Autowired
    private JdbcDAO dao;


    protected JdbcDAO getDAO() {
        if (null == dao) {
            dao = JdbcDAO.instance();
        }
        return dao;
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 当前登录的Subject授予角色和权限
        String sql = "select * from t_user where login = ?";
        String username = (String) super.getAvailablePrincipal(principals);
        User exits = getDAO().queryForObject(User.class, sql, username);
        if (null != exits) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.setRoles(new HashSet<String>(Arrays.asList(exits.getRole())));
            return info;
        } else {
            return null;
        }
    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {
        // 验证当前登录的Subject
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        return new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(),
            token.getUsername());
    }

}
